package org.study.shardingsphere.boot.algorithm;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;

import java.util.Collection;
import java.util.Properties;

/**
 * 自定义 Hint 分库策略。
 * 参考 https://www.yisu.com/zixun/598542.html
 *
 * @author Administrator
 * @date 2022-03-10
 */
@Slf4j
public class HintShardingAlgorithm4TableDemo implements HintShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> tableNames, HintShardingValue<Long> hintShardingValue) {
        log.info("tableNames：{}，hintShardingValue：{}", JSON.toJSONString(tableNames), JSON.toJSONString(hintShardingValue));
        Collection<String> result = Sets.newConcurrentHashSet();
        Collection<Long> orderIds = hintShardingValue.getValues();
        for (Long orderId : orderIds) {
            if (orderId == 2L) {
                result.add("t_order_0");
            }
        }
        // 根据传进来的分片值，路由到对应的物理表
        return result;
    }

    @Override
    public String getType() {
        return "HINT_TABLE_LONG";
    }

    @Override
    public void init(Properties props) {
    }
}
